package com.dominator.utils.wechat.pay;

import com.dominFramework.core.id.SystemIdUtils;
import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.utils.JsonUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.exception.ApiException;
import com.dominator.utils.system.PropertiesLoader;
import com.dominator.utils.wechat.utils.*;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.util.SortedMap;
import java.util.TreeMap;

@Slf4j
public class WechatEnterprisePayUtils {


    private static String  charset="UTF-8";

    public static PropertiesLoader propertiesLoader = new PropertiesLoader("sysconfig.properties");


    public static String pkcs8 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArcnmoFXRGheYhgV6/9mH" +
            "UwaU2IpavZWjFI+BDAYOGmkvCzcEKd61abNssW4DAhYM04BBxmfEee/bJt/yheM0" +
            "SGiUL4xPnbxDFKuC5mbReBL4KN8NLnsomdbzxIN1pk20HDWfCIhsX0Uo1awPO2CF" +
            "xpprRwhWh1Xof9WoeWaZ6yMpWPHCxnQC7uvOt8vb/wBc6H+mvKisVgOlkVVOl6Dg" +
            "AGk7rFtfWZ8BULrN2LVyW7I8Rorz+OWCuxCtTlshKZqCMfvq5bEexWrGxlNPqJrJ" +
            "Hc3coqAkcYZwuOwvSa0qAFJAd0BlJgAlUnMhIw7bZ08P/PzMyWAzkyGHxF7Y5rVZ" +
            "YwIDAQAB";


    /**
     * 支付到银行卡
     *
     * @param dto
     * @throws ApiException
     */
    public static void PaymentToBankCard(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "realName,bankNum,bankCode,amount,desc");
        String source = null;
        //source=dto.getString("realName");
        try {
            source = new String(dto.getString("realName").getBytes("utf-8"), charset);
            log.info("=========" + source);
        } catch (UnsupportedEncodingException e) {
            throw new ApiException(ReqEnums.WECHAT_ENC_TRUE_NAME_ERROR);
        }
        String bankNum = dto.getString("bankNum");
        String bank_code = dto.getString("bankCode");
        String amount = dto.getString("amount");
        String desc = dto.getString("desc");
        // 注意 这里的 publicKeyPKCS8 是上一步获取微信支付公钥后经openssl 转化成PKCS8格式的公钥
        String publicKeyPKCS8 = pkcs8;
        String enc_true_name = null;
        try {
            enc_true_name = GetRSA.getRSA(source, publicKeyPKCS8);
        } catch (Exception e) {
            throw new ApiException(ReqEnums.WECHAT_ENC_TRUE_NAME_ERROR);
        }
        String enc_bank_no = null;
        try {
            enc_bank_no = GetRSA.getRSA(bankNum, publicKeyPKCS8);
        } catch (Exception e) {
            throw new ApiException(ReqEnums.WECHAT_ENC_BANK_NO_ERROR);
        }
        String partner_trade_no = SystemIdUtils.uuid();
        String nonce_str1 = StringUtils.getStrRandom(28);
        // 获取签名
        SortedMap<Object, Object> parameters1 = new TreeMap<Object, Object>();
        parameters1.put("mch_id", propertiesLoader.getProperty("wx_mch_public_id"));
        parameters1.put("partner_trade_no", partner_trade_no);
        parameters1.put("nonce_str", nonce_str1);
        parameters1.put("enc_bank_no", enc_bank_no);
        parameters1.put("enc_true_name", enc_true_name);
        parameters1.put("bank_code", bank_code);
        parameters1.put("amount", amount);
        parameters1.put("desc", desc);
        String sign1 = SignUtils.creatSign(charset, parameters1);
        // 请求企业付款
        TreeMap<String, String> tmap1 = new TreeMap<String, String>();
        tmap1.put("mch_id", propertiesLoader.getProperty("wx_mch_public_id"));
        tmap1.put("partner_trade_no", partner_trade_no);
        tmap1.put("nonce_str", nonce_str1);
        tmap1.put("enc_bank_no", enc_bank_no);
        tmap1.put("enc_true_name", enc_true_name);
        tmap1.put("bank_code", bank_code);
        tmap1.put("amount", amount);
        tmap1.put("desc", desc);
        tmap1.put("sign", sign1);
        String xml2 = null;
        try {
            xml2 = XMLUtils.getRequestXml(tmap1);
            log.info(xml2);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(ReqEnums.WECHAT_GET_REQUEST_XML_ERROR);
        }
        String xml3 = null;
        try {
            xml3 = HttpClientCustomSSL.httpClientResultBank(xml2);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(ReqEnums.WECHAT_HTTP_CLIENT_RESULT_BANK_ERROR);
        }
        //解析回文
        System.out.println(xml3);
        String res = XMLUtils.xmlToJson(xml3);
        Dto wxDto = JsonUtils.toDto(res);
        if (!"SUCCESS".equals(wxDto.getString("return_code"))) {
            throw new ApiException(ReqEnums.WECHAT_MCH_PAY_ERROR);
        }
        if (!"SUCCESS".equals(wxDto.getString("result_code"))) {
            String errorCodeDes = wxDto.getString("err_code_des");
            String errCode = wxDto.getString("err_code");
            log.error(xml3);
            log.error("errorCodeDes:" + errorCodeDes + "errCode:" + errCode);
            throw new ApiException(ReqEnums.WECHAT_MCH_PAY_ERROR);
        }
         return;
    }


}
